package com.yilin.platform.base_core.commons.utils;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class StampFactory {

    private static StampFactory instance;

    public static StampFactory getInstance() {
        if (instance == null) instance = new StampFactory();
        return instance;
    }

    ///白底抠除范围

    public static void main(String[] args) {
        //得到透明底图片
        try {
            BufferedImage bufferedImage = StampFactory.getInstance().stampCutout(ImageIO.read(new File("C:\\Users\\admin\\Desktop\\Export\\001.jpg")));
            if (bufferedImage == null) return;
            bufferedImage = StampFactory.getInstance().cropImage(bufferedImage);
            if (bufferedImage == null) return;
            ImageIO.write(bufferedImage, "png", new File("C:\\Users\\admin\\Desktop\\Export\\002.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }

//        try {
//            String base64 = SealUtils.companyCircleSeal("贵州极舜货运有限公司", ColorEnum.RED, FontEnum.SONGTI,"1234567899876","电子合同专用");
//            if (base64.contains("data:image/png;base64,")) base64 = base64.split("data:image/png;base64,")[1];
//            BufferedImage bufferedImage = ImageEditUtils.base64ToBufferedImage(base64);
//            ImageIO.write(bufferedImage, "png", new File("C:\\Users\\admin\\Desktop\\stamp_png\\009.png"));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

//        BufferedImage image = Graphics2DUtil.startGraphics2D("贵州极舜货运有限公司","合同专用章","");
//
//        String filePath = "";
//        try {
//            filePath = "C:\\Users\\admin\\Desktop\\stamp_png\\"+new Date().getTime()+".png";
//            ImageIO.write(image, "png", new File(filePath)); //将其保存在D:\\下，得有这个目录
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }

    }


    public  int color_range = 100;//

    public  BufferedImage stampCutout(BufferedImage image) {
        // 高度和宽度
        int height = image.getHeight();
        int width = image.getWidth();
        // 生产背景透明和内容透明的图片
        ImageIcon imageIcon = new ImageIcon(image);
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics(); // 获取画笔
        g2D.drawImage(imageIcon.getImage(), 0, 0, null); // 绘制Image的图片，使用了imageIcon.getImage()，目的就是得到image,直接使用image就可以的
        int i=1;
        int alpha = 0; // 图片透明度
        // 外层遍历是Y轴的像素
        for (int y = bufferedImage.getMinY(); y < bufferedImage.getHeight(); y++) {
            // 内层遍历是X轴的像素
            for (int x = bufferedImage.getMinX(); x < bufferedImage.getWidth(); x++) {
                int rgb = bufferedImage.getRGB(x, y);
                // 对当前颜色判断是否在指定区间内
                if (colorInRange(rgb)){
                    // #AARRGGBB 最前两位为透明度
                    rgb = (alpha << 24) | (rgb & 0x00ffffff);
                    bufferedImage.setRGB(x, y, rgb);
                    alpha = 0;

                }else{
                    // 设置为不透明
                    alpha = 255;
                    // #AARRGGBB 最前两位为透明度
                    rgb = (alpha << 24) | (0xff0000);//红色构图
                    //rgb = (alpha << 24) | (0x000000);//黑色构图
                    bufferedImage.setRGB(x, y, rgb);
                }
            }
        }
        // 绘制设置了RGB的新图片,这一步感觉不用也可以只是透明地方的深浅有变化而已，就像蒙了两层的感觉
        g2D.drawImage(bufferedImage, 0, 0, null);
        return bufferedImage;
    }


    /**
     * 自动裁剪透明区域（含黑色）
     */
    public BufferedImage cropImage(BufferedImage image) {
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics(); // 获取画笔
        g2D.drawImage(new ImageIcon(image).getImage(), 0, 0, null); // 绘制Image的图片，使用了imageIcon.getImage()，目的就是得到image,直接使用image就可以的
//            System.out.println("原图片宽度" + width);
//            System.out.println("原图片高度" + height);
        int[] arr = bufferedImageToIntArray(bufferedImage, width, height);
        // BufferedImage newBufferedImage = bufferedImage.getSubimage(arr[0] - blank, arr[1] - blank, arr[2] + blank * 2, arr[3] + blank * 2);
        if (arr == null) return bufferedImage;
        return bufferedImage.getSubimage(arr[0], arr[1], arr[2], arr[3]);
    }

    // 判断是背景还是内容
    private  boolean colorInRange(int color) {
        int red = (color & 0xff0000) >> 16;// 获取color(RGB)中R位
        int green = (color & 0x00ff00) >> 8;// 获取color(RGB)中G位
        int blue = (color & 0x0000ff);// 获取color(RGB)中B位
        //System.out.println("red=="+red   +"green=="+green  +"blue=="+blue);
        // 通过RGB三分量来判断当前颜色是否在指定的颜色区间内
        if (red >= color_range && green >= color_range && blue >= color_range){
            return true;
        }
        System.out.println("red**"+red   +"green**"+green  +"blue**"+blue);
        return false;
    }

    ///获取非透明区矩形坐标
    private static int[] bufferedImageToIntArray(BufferedImage image, int width, int height) {
        try {
            int rgb;
            int x1 = width;
            int y1 = height;
            int x2 = 0;
            int y2 = 0;
            int tempX, tempY;
            // 外层遍历是Y轴的像素
            for (int y = image.getMinY(); y < image.getHeight(); y++) {
                // 内层遍历是X轴的像素
                for (int x = image.getMinX(); x < image.getWidth(); x++) {
                    rgb = image.getRGB(x, y);
                    if (rgb != 0) {
                        tempX = x;
                        tempY = y;
                        // 计算最左侧
                        if (x1 >= tempX) x1 = tempX;
                        // 计算最右侧
                        if (x2 <= tempX) x2 = tempX;
                        // 计算最下方
                        if (y2 <= tempY) y2 = tempY;
                        // 计算最上方
                        if (y1 >= tempY) y1 = tempY;
                    }
                }
            }
            return new int[]{x1, y1, x2 - x1, y2 - y1};
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
